<template>
    <div>
        <path-bar @pathClick="pathClick" ref="pathBar" :list="pathList"></path-bar>
        <file-table @fileClick="fileClick" @folderClick="folderClick" :list="list"></file-table>
    </div>
</template>

<script>
import API from '../api'
import FileTable from '../components/FileTable.vue'
import PathBar from '../components/PathBar.vue'
import File from '../utils/file'
import { remote } from 'electron'
import fs from 'fs'
export default {
    components: { FileTable, PathBar },
    props: {
        name: {
            type: String,
            default: '公共网盘'
        },
        uid: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            list: [],
            pathList: []
        }
    },
    mounted() {
        this.pathList.push({
            name: this.name
        })
        this.getFileList()
    },
    methods: {
        pathClick(item, i) {
            this.pathList.splice(i + 1)
            this.getFileList(this.uid, this.$refs.pathBar.makeUrlPath(1))
        },
        folderClick(item) {
            this.pathList.push({ name: item.name })
            this.getFileList(this.uid, this.$refs.pathBar.makeUrlPath(1))
        },
        async fileClick(item) {
            console.log(item.suffix)
            // let path = null
            switch (item.suffix) {
            case 'mp4':
            case 'mkv':
            case 'mp3':
                this.openVideoPlayer(item)
                break

            default:
                this.cacheFile(item)
                // path = await this.showDownloadPathSelectDialog()
                // this.$root.$emit('download', item, path)
                break
            }
        },
        async cacheFile(item) {
            this.loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            })
            const path = remote.app.getPath('userData') + '\\FileCache'
            const dirBool = await new Promise((resolve, reject) => {
                fs.access(path, fs.constants.R_OK, function(err) {
                    if (err) {
                        console.log('文件和目录不存在')
                        resolve(false)
                    } else {
                        resolve(true)
                    }
                })
            })
            if (!dirBool) {
                fs.mkdirSync(path)
            }
            const bool = await new Promise((resolve, reject) => {
                fs.access(path + `\\${item.name}`, fs.constants.R_OK, function(err) {
                    if (err) {
                        console.log('文件和目录不存在')
                        resolve(false)
                    } else {
                        resolve(true)
                    }
                })
            })
            if (bool) {
                this.loading.close()
                remote.shell.openPath(path + `\\${item.name}`)
                return
            }
            File.downloadFile({
                remoteFile: API.getServer() + encodeURI(API.resource.downloadFileByMD5(item.md5, item.name).url),
                localFile: path + `\\${item.name}`,
                onProgress: (received, total, length) => {
                    const percentage = (received * 100) / total
                    this.loading.text = parseInt(percentage) + '%'
                }
            }).then(() => {
                this.loading.close()
                remote.shell.openPath(path + `\\${item.name}`)
            })
        },
        openVideoPlayer(item) {
            const BrowserWindow = remote.BrowserWindow
            let winA = new BrowserWindow({
                width: 1000,
                height: 600,
                webPreferences: {
                    contextIsolation: false,
                    nodeIntegration: true
                }
            })
            const winURL = process.env.NODE_ENV === 'development'
                ? 'http://localhost:8080/'
                : `file://${__dirname}/index.html`
            console.log(winURL + '#/videoplayer')
            winA.loadURL(winURL + '#/videoplayer?url=' + API.getServer() + encodeURI(API.resource.downloadFileByMD5(item.md5, '').url))
            // winA.webContents.openDevTools()
            winA.on('close', () => {
                winA = null
            })
        },
        async showDownloadPathSelectDialog() {
            const res = await remote.dialog.showOpenDialog({
                // 选择操作，此处是打开文件夹
                properties: [
                    'openDirectory'
                ]
            })
            return res.filePaths[0]
        },
        async getFileList(uid = this.uid, path = '') {
            const res = await this.axios(API.file.getFileList(uid, encodeURI(path)))
            console.log(res)
            if (res.data.data.length < 2) {
                res.data.data.unshift([])
            }
            this.list = res.data.data
        }
    }
}
</script>

<style>

</style>
